/**
 * 
 */
package com.swd2010.mobileSearch.network;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.swd2010.mobileSearch.data.PersonBean;

import android.util.Log;


/**
 * @author haui
 *
 */
public class PersonByIdWebservice {

	
	//Haui
	
	private static final String classNameForLog = "PersonByIdWebservice";
    


	
	
	public static PersonBean get(String id) {
		
				
	    PersonBean pB = new PersonBean();

	    ConnectInformation conInformation = new ConnectInformation();
	    
	    
	    HttpURLConnection conn = null;
	    StringBuilder jsonResults = new StringBuilder();

	    
	    
	    try {
	    	
	        	        
	    	URL url = conInformation.getSinglePersonById(id);
//Log.e(url.toString(),url.toString());	    	
	        conn = (HttpURLConnection) url.openConnection();
	        InputStreamReader in = new InputStreamReader(conn.getInputStream());
	        
	        
	        // Load the results into a StringBuilder
	        int read;
	        
	        char[] buff = new char[1024];
	        
	        while ((read = in.read(buff)) != -1) {
	            jsonResults.append(buff, 0, read);
	        }
	        
	    } catch (MalformedURLException e) {
	    	
	        Log.e(classNameForLog, "Error: ", e);
	        return pB;
	        
	    } catch (IOException e) {
	    	
	        Log.e(classNameForLog, "Error: ", e);
	        return pB;
	        
	    } finally {
	    	
	        if (conn != null) {
	            conn.disconnect();
	        }
	        
	    }

	    try {
	    	
	    	
	    	if ( jsonResults.toString().equalsIgnoreCase("NULL") )
	    		return pB;
	    	
	    	
	        // Create a JSON object hierarchy from the results
	        JSONObject jsonObj = new JSONObject(jsonResults.toString());
	        //JSONArray predsJsonArray = jsonObj.getJSONArray("personBean");

	        // Extract the Place descriptions from the results
	        //resultList = new ArrayList<String>(predsJsonArray.length());
	        
	        //for (int i = 0; i < predsJsonArray.length(); i++) {

	        	
	        pB.setFullNameWithDegress( (jsonObj.getString("fullNameWithDegress") ) );
	        pB.setAdditionalInformation( (jsonObj.getString("additionalInformation") ) );
	        pB.seteMail( (jsonObj.getString("eMail") ) );
	        pB.setAddress( (jsonObj.getString("address") ) );
	        pB.setId( (jsonObj.getString("id") ) );
	        pB.setTelephoneNr( (jsonObj.getString("telephoneNr") ) );
	            	        
	        //}
	        
	    } catch (JSONException e) {
	    	
	    	
	        Log.e(classNameForLog, "Cannot process JSON results", e);
	        
	        
	    }
	    
	    return pB;
	
	}	
	
	
}
